package org.wx.thread;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

/**
 * @description: join 测试
 * sub.join() 方法
 * 首先main线程获取到sub线程对象的锁
 * 检查sub线程是否存活
 * 如果存活就进行wait()
 * 当sub线程结束的时候，会调用notifyAll 方法将获得sub线程对象的锁唤醒
 * #thread.cpp
 * //线程结束，调用该方法
 * void JavaThread::exit(bool destroy_vm, ExitType exit_type) {
 *   ...
 *   ensure_join(this);
 *   ...
 * }
 *
 * static void ensure_join(JavaThread* thread) {
 *   ...
 *   ObjectLocker lock(threadObj, thread);
 *   ...
 *   //唤醒等待在thread对象上的线程
 *   lock.notify_all(thread);
 *   ...
 * }
 *
 * #ObjectSynchronizer.hpp
 * void notify_all(TRAPS)      { ObjectSynchronizer::notifyall(_obj,    CHECK); }
 *
 * main 线程被唤醒 ，再执行后面的代码
 *
 *
 * @author: wangxun
 * @createDate: 2021/4/8
 * @version: 1.0
 */
@Slf4j
public class JoinTest {
    static class SubThread extends Thread{

        public SubThread( String name) {
            super(name);
        }

        @Override
        public void run() {
            log.info("子线程执行");
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        final SubThread subThread = new SubThread("sub");
        subThread.start();
        try {
            subThread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log.info("主线程执行");
    }

}
